package com.xiaozhengkeji.blogsuper.services.impl;



import com.xiaozhengkeji.blogsuper.services.EMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service("EMailService")
public class EMailServiceIMP implements EMailService {
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    JavaMailSender javaMailSender;

    @Async("taskExecutor")
    @Override
    public void sendRegisterEMail(String toEMail, String username, String verificationCode) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("欢迎注册小正的个人博客");
            helper.setFrom("blog@xiaozhengkeji.com");
            helper.setTo(toEMail);
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("v1", username + " 欢迎注册!请在10分钟内完成注册!");
            context.setVariable("v2", "您注册帐户" + username + " 所需的邮箱令牌验证码 为：");
            context.setVariable("verificationCode", verificationCode);
            String process = templateEngine.process("register.html", context);
            helper.setText(process, true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
